//
//  EquipmentListViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/11.
//

#import "EquipmentListViewController.h"
#import "EquipmentListCell.h"
#import "ConfigNetworkViewController.h"

@interface EquipmentListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, strong) NSArray *dataSource;
@end

@implementation EquipmentListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Equipment list";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self reloadData];
}

+ (instancetype)instance{
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"EquipmentListViewController"];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LFWeakSelf(self)
    EquipmentListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EquipmentListCell"];
    DeviceModel *device = self.dataSource[indexPath.row];
    [cell fillWithModel:device];
    [cell handleUserAction:^(BOOL isUnbind) {
        if (isUnbind) {
            LFWeakSelf(self)
            if (device.deviceSN.length != 0) {
                NSDictionary *parameters = @{@"sn" : device.deviceSN};
                [[HttpRequest request] sendRequestWithHttpMethod:E_HTTP_REQUEST_METHOD_GET URLPath:@"/lefu/wifi/app/clearDeviceData" parameters: parameters completionHandler:^(id  _Nonnull data, NSError * _Nonnull error) {
                    [ProgressHud showText:@"unbind success"];
                    [self deleteDevice:device];
                    [weakself reloadData];
                }];
            }else{
                [ProgressHud showText:@"unbind success"];
                [self deleteDevice:device];
                [weakself reloadData];
            }
        }else{
            ConfigNetworkViewController *vc = [ConfigNetworkViewController instance];
            vc.device = device;
            [weakself.navigationController pushViewController:vc animated:YES];
        }
    }];
    return cell;

}


- (void)reloadData{
    self.dataSource = [DeviceModel allObjects];
    [self.table reloadData];
}

- (void)deleteDevice:(DeviceModel *)device{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm deleteObject:device];
    }];
}

@end
